package client_core

import (
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/client_core/config"
	"github.com/chicken-team-outside/chicken_transmission/client_core/util"
	"github.com/chicken-team-outside/chicken_transmission/proxy_server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func initLocalDriver(group *gin.RouterGroup) {
	group.POST("/enable", setLocalDiskDriverEnabled)
	group.GET("/config", getLocalConfig)
	group.POST("/config", saveLocalDiskDriver)
}

func tryLoadAndSetLocalDriver() error {
	localDriver, err := util.CreateLocalDriver(config.LocalDiskDriverInfo())
	if err != nil {
		return err
	} else {
		sfsClient.SetLocal(localDriver)
	}
	return nil
}

func saveLocalDiskDriver(ctx *gin.Context) {
	info := &config.DriverInfo{}
	err := ctx.ShouldBindJSON(info)
	if err != nil {
		BadRequest(ctx, "参数错误")
		return
	}
	localDriver, err := util.CreateLocalDriver(info)
	if err != nil {
		zap.L().Warn("create local driver failed", zap.Error(err))
		BadRequest(ctx, "无法应用配置")
		return
	}
	err = config.SaveLocalDiskDriver(info)
	if err != nil {
		zap.L().Error("save local disk driver failed", zap.Error(err))
		BadRequest(ctx, "保存配置失败")
		return
	}
	if config.LocalDiskEnabled() {
		sfsClient.SetLocal(localDriver)
	} else {
		localDriver.Close()
	}
	Success(ctx, nil, "配置已应用")
	return
}

func SetLocalDiskDriverEnabled(enabled bool) error {
	if enabled {
		err := tryLoadAndSetLocalDriver()
		if err != nil {
			return err
		}
	} else {
		current := sfsClient.GetLocal()
		sfsClient.SetLocal(nil)
		if current != nil {
			if err := current.Close(); err != nil {
				zap.L().Error("failed to close local driver", zap.Error(err))
			}
		}
	}
	err := config.SaveLocalDiskEnabled(enabled)
	if err != nil {
		return fmt.Errorf("failed to save local disk enabled status: %w", err)
	}
	return nil
}

func setLocalDiskDriverEnabled(ctx *gin.Context) {
	var enabled bool
	err := ctx.BindJSON(&enabled)
	if err != nil {
		BadRequest(ctx, "参数错误")
		return
	}
	err = SetLocalDiskDriverEnabled(enabled)
	if err != nil {
		zap.L().Error("failed to set local disk driver enabled", zap.Error(err), zap.Bool("enabled", enabled))
		utils.BadRequest(ctx, "设置失败")
	} else {
		utils.Success(ctx, "设置成功", nil)
	}
}

func getLocalConfig(ctx *gin.Context) {
	Success(ctx, gin.H{
		"enabled": config.LocalDiskEnabled(),
		"config":  config.LocalDiskDriverInfo(),
	}, "成功")
}
